/*
 * Assingment05b.c
 *
 * Created: 4/17/2015 8:57:53 PM
 *  Author: Jeevake Attapattu
 */ 

#define F_CPU 8000000UL //XTAL = 8MHZ
#include <avr/io.h>
#include <util/delay.h>


int ReadADC(uint16_t ADCchannel)
{
	int ADCval;
	ADMUX = (ADMUX & 0xF0)|(ADCchannel & 0x0F);//select channel
	ADCSRA |= 1<<ADSC;//start conversion
	while(ADCSRA & (1<<ADSC));//wait for conversion
	ADCval = ADC>>6;//use only upper 10 bits of 16 bits
	ADCval = (int)ADCval*5/1024;//Vin=ADC*Vref/1024
	ADCSRA 	|= 	1<<ADSC;
	return ADCval;//return adc value 0-5
}



int main()
{
	//initialize ADC
	ADMUX = (1<<REFS0)|(1<<ADLAR);//set Vref to 5V and left justify
	ADCSRA =(1<<ADIE)|(1<<ADEN);//set prescalar to 2, enable ADC interrupt and enable ADC 
	ADCSRB = 0x00;//set ADC constant conversion
	int delay;
	DDRB = 0xFF;//set port B output
	
	while(1)
	{
		//read adc channel 0
		delay = ReadADC(0);
		//turn clockwise 
		//use adc value to change delay
		PORTB = 0X66;
		for (int i = 0; i<delay; i++)
		_delay_ms(20);
		PORTB = 0xCC;
		for (int j = 0; j<delay; j++)
		_delay_ms(20);
		PORTB = 0x99;
		for (int k = 0; k<delay; k++)
		_delay_ms(20);
		PORTB = 0x33;
		for (int l = 0; l<delay; l++)
		_delay_ms(20);	
	}
	return 0;
}